package droid.net.playcabbage.asynctask;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import droid.net.playcabbage.activity.CabbageActivity;
import droid.net.playcabbage.xxx.NewList;

import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;

public class FetchJSONAsyncTask extends AsyncTask<String,Integer,String> {
	
	private CabbageActivity activity;
	
	public FetchJSONAsyncTask(CabbageActivity sourceActivity) {
		activity = sourceActivity;
	}

	@Override
	protected String doInBackground(String... string) {
		StringBuilder builder = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(string[0]);
		try {
			HttpResponse response = client.execute(httpGet);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
			} else {
				Log.e(NewList.class.toString(), "Failed to download file");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return builder.toString();
	}
	
	@Override
    protected void onPostExecute(String result) {
		activity.buildList(result);
    }

}
